package light.head.controller.oa;

import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.config.ConfigParm;
import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.oa.ContractDAO;
import light.head.dao.oa.ContractTypeDAO;
import light.head.dao.sys.FileDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.DownLoadUtils;
import light.head.model.Contract;
import light.head.model.ContractType;
import light.head.model.FileInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = Url.C_CONTRACT)
public class ContractController extends SupporterController{

	private final static String contract_file = "upload/contractFile/";
	private ContractDAO contractDAO;
	private ContractTypeDAO ctDAO;
	private FileDAO fDAO;
	
	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.CONTRACT_INIT);
	}
	
	
	@RequestMapping(value = Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.NAME, Parm.TNAME, Parm.OC);
		map.put(Parm.OC, cu_organCode(request).toString());
		if(contractDAO.findByMap(map, pb) == RESULT.SUCCESS) {
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		return new ModelAndView(Url.CONTRACT_LIST);
	}


	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		if(null == cu_organCode(request)) {
			PageBean pb = createPageBean(request);
			request.setAttribute(Parm.PAGE_BEAN, pb);
			return new ModelAndView(Url.CONTRACT_INIT);
		}
		List<ContractType> typeList = ctDAO.findByOc(cu_organCode(request));
		if (null != typeList && typeList.size() > 0) {
			StringBuffer result = new StringBuffer("[");
			
			for (ContractType type : typeList){
				result.append("{");
				result.append("\"tname\":\"" + type.getName() +"\",");
				result.append("\"tc\":\"" + type.getCode() +"\"");
				result.append("},");
			}
			result.deleteCharAt(result.length() - 1).append("]");
			request.setAttribute(Parm.TYPE, result.toString());
		} 
		String code = request.getParameter(Parm.CODE);
		if(isNotNull(code)) {
			Contract con = contractDAO.get(Integer.parseInt(code));
			request.setAttribute(Parm.CONTRACT, con);
		}
		return new ModelAndView(Url.CONTRACT_EDIT);
	}
	
	@RequestMapping(value = Url.SAVE)
	public void save(Contract con, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		if(null == con.getCode()) {
			if(con.getName().equals("")) {
				print(response, Msg.NULL_NAME);
				return;
			}if(con.getUuid().equals("")) {
				print(response, Msg.NULL_TYPE);
				return;
			}if(con.getEnd() == null) {
				print(response, Msg.NULL_TIME);
				return;
			}
			List<ContractType> iac = ctDAO.findByNameOc(con.getTname(), cu_organCode(request));
			if (iac == null || iac.size() == 0)  {
				ContractType atn = new ContractType();
				atn.setCu(cu_code(request));
				atn.setCt(new Date());
				atn.setDeleted(false);
				atn.setName(con.getTname());
				atn.setOc(cu_organCode(request));
				ctDAO.add(atn);
				con.setTc(atn.getCode());
			}
			con.setBusiness(con.getBusiness());
			con.setExt(con.getExt());
			con.setName(con.getName());
			con.setSize(con.getSize());
			con.setUuid(con.getUuid());
			con.setCt(new Date());
			con.setCu(cu_code(request));
			con.setDeleted(false);
			con.setOc(cu_organCode(request));
			result = contractDAO.add(con);
		}else {
			List<ContractType> iac = ctDAO.findByNameOc(con.getTname(), cu_organCode(request));
			if (iac == null || iac.size() == 0)  {
				ContractType atn = new ContractType();
				atn.setCu(cu_code(request));
				atn.setCt(new Date());
				atn.setDeleted(false);
				atn.setName(con.getTname());
				atn.setOc(con.getOc());
				ctDAO.add(atn);
				con.setTc(atn.getCode());
			}
			Contract cona = contractDAO.get(con.getCode());
			cona.setBusiness(con.getBusiness());
			cona.setEnd(con.getEnd());
			cona.setTc(con.getTc());
			cona.setUc(con.getUc());
			con.setExt(con.getExt());
			cona.setName(con.getName());
			cona.setSize(con.getSize());
			cona.setUuid(con.getUuid());
			result = contractDAO.upd(cona);
		}
		
		if(RESULT.SUCCESS == result) {
			print(response, Msg.SUCCESS);
		}else {
			print(response, Msg.ERROR);
		}
	}
	
	@RequestMapping(value = Url.DELETE)
	public void delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		
		Contract con = contractDAO.get(Integer.parseInt(code));
		con.setDeleted(true);
		if (contractDAO.update(con) == RESULT.SUCCESS) {
			print(response, Msg.SUCCESS);
		} else 
			print(response, Msg.ERROR);
	}

	@Transactional
	@RequestMapping(Url.UPLOADS)
	public void uploads(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		List<MultipartFile> files = multipartRequest.getFiles("files");

		StringBuffer result = new StringBuffer("");
		if (null != files && files.size() > 0) {

			String name = null;
			String ext = null;
			String uuid = null;
			String path = null;
			String savePath = null;
			UUID u = null;

			for (MultipartFile mf : files) {
				name = mf.getOriginalFilename();
				System.out.println(mf.getOriginalFilename() + "--" + mf.getName());
				if (isNotNull(name)) {
					ext = name.substring(name.lastIndexOf('.') + 1);
					if (!ext.toUpperCase().equals(Sys.JPG)
							&& !ext.toUpperCase().equals(Sys.GIF)
							&& !ext.toUpperCase().equals(Sys.JPEG)
							&& !ext.toUpperCase().equals(Sys.BMP)
							&& !ext.toUpperCase().equals(Sys.PNG)
							&& !ext.toUpperCase().equals(Sys.XLSX)
							&& !ext.toUpperCase().equals(Sys.XLS)
							&& !ext.toUpperCase().equals(Sys.DOCX)
							&& !ext.toUpperCase().equals(Sys.DOC)
							&& !ext.toUpperCase().equals(Sys.PDF)
							&& !ext.toUpperCase().equals(Sys.PPT)
							&& !ext.toUpperCase().equals(Sys.RAR)
							&& !ext.toUpperCase().equals(Sys.ZIP)) {
						print(response, Msg.J_FILE_TYPE_ERROR);
						return;
					}
					name = name.substring(0, name.lastIndexOf('.'));

					u = UUID.randomUUID();
					uuid = u.toString().replace("-", "");
					path = contract_file + uuid + Sys.DOT + ext;
					savePath = ConfigParm.getProjectPath() + path;
					FileOutputStream fo;
					int size = 0;
					
				
					try {
						fo = new FileOutputStream(savePath);
						size = mf.getBytes().length;
						fo.write(mf.getBytes());
						fo.close();
					} catch (Exception e) {
						print(response, Msg.ERROR);
						e.printStackTrace();
					}

					
					FileInfo f = new FileInfo();
					f.setDeleted(false);
					f.setUuid(uuid);
					f.setExt(ext);
					f.setName(name);
					f.setCt(new Date());
					f.setType(Sys.B_ONE);
					f.setModule(Parm.CONTRACT_ANNEX);
					f.setCu(cu_code(request));
					f.setOc(cu_organCode(request));
					f.setSize(size);
					contractDAO.add(f);

					result.append("{\"name\":\"" + name + "\",\"uuid\":\"" + uuid + "\",\"ext\":\"" + ext + "\",\"size\":\"" + size + "\",\"path\":\"" + uuid + Sys.DOT + ext + "\"},");
				}
			}

			result.insert(0, "{\"result\":\"success\",\"list\":[").deleteCharAt(result.length() - 1).append("]}");
			print(response, result.toString());
		} else {
			result.append("{\"result\":\"not_find_file\"}");
		}
	}
	
	@Transactional
	@RequestMapping(value = Url.DOWNLOAD)
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			return;
		}
		Contract con = contractDAO.findByUuid(code);
		FileInfo f = fDAO.getByUuid(code);
		if (null != f) {
			DownLoadUtils.downLoad(contract_file, con.getName(), f.getUuid(), f.getExt(), response);
		}
		
	}
	
	@Autowired
	public void setContractDAO(ContractDAO contractDAO) {
		this.contractDAO = contractDAO;
	}

	@Autowired
	public void setCtDAO(ContractTypeDAO ctDAO) {
		this.ctDAO = ctDAO;
	}

	@Autowired
	public void setfDAO(FileDAO fDAO) {
		this.fDAO = fDAO;
	}
	
	
}
